package cn.bigfire.wzdj.frame;

import cn.bigfire.wzdj.action.WZDJCaller;
import cn.bigfire.wzdj.action.WZDJSender;
import cn.bigfire.wzdj.pojo.bo.WZDJPack;
import cn.bigfire.wzdj.pojo.datao.LocalDO;
import cn.bigfire.wzdj.pojo.httpVo.*;
import cn.bigfire.wzdj.pojo.srcVo.Wzdj;
import cn.bigfire.wzdj.pojo.vo.DHWzdjCfg;
import cn.bigfire.wzdj.pojo.vo.Goods;
import cn.bigfire.wzdj.pojo.vo.GoodsVO;
import cn.bigfire.wzdj.service.WZDJService;
import cn.bigfire.wzdj.util.*;
import cn.bigfire.wzdj.util.sign.WZDJAppSign;
import cn.bigfire.wzdj.util.sign.WZDJSign;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.ThrowableUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Slf4j
public class WZDJMainFrame extends JFrame {

    public static QrCanvas qrCanvas = new QrCanvas();

    public static JPanel dsJpanel = new JPanel();
    public static QrCanvas dsCanvas = new QrCanvas();

    public static JLabel qrStatusLabel = new JLabel("左侧选择添加WX号|APP号");

    //账号
    public static JTextField accountJTF = new JTextField(10);
    public static JTextField passwordJTF = new JTextField(10);


    public static JComboBox<String> accountBox = new JComboBox<>();

    public static JComboBox<String> modelBox = new JComboBox<>();


//    public static JLabel uidJLabel = new JLabel("用户id:");
//    public static JLabel uNameJLabel = new JLabel("用户名:");
//    public static JLabel vipJLabel = new JLabel("vip:");
//    public static JLabel lvJLabel = new JLabel("等级:");



    public static JLabel goldJlabel = new JLabel("金币:");
    public static JLabel diamondJlabel = new JLabel("钻石:");
    public static JLabel mythicStoneJlabel = new JLabel("万能:");
    public static JLabel mineKeyJlabel = new JLabel("锤子:");
    public static JLabel recruitKeyJlabel = new JLabel("招募:");
    public static JLabel recruitGemJlabel = new JLabel("招募(高):");
    public static JLabel energyJlabel = new JLabel("体力:");
    public static JLabel energyNextJlabel = new JLabel("刷新:");

    public static JButton shopRefreshBtn = new JButton("刷店");;
    public static JLabel goodLabel2 = new JLabel("商品2:");
    public static JLabel goodLabel3 = new JLabel("商品3:");
    public static JLabel goodLabel4 = new JLabel("商品4:");
    public static JLabel goodLabel5 = new JLabel("商品5:");
    public static JLabel goodLabel6 = new JLabel("商品6:");

    public static JLabel goodLabel7 = new JLabel("买体力:");

    public static ArrayList<JLabel> goodLabels = new ArrayList<>();


    public static JLabel callCostJlabel = new JLabel("召唤需要:0");
    public static JLabel enhance1Jlabel = new JLabel("强蓝色lv:0");
    public static JLabel enhance2Jlabel = new JLabel("强紫色lv:0");
    public static JLabel enhance3Jlabel = new JLabel("强金橙lv:0");
    public static JLabel enhance4Jlabel = new JLabel("召概率lv:0");


    public static JLabel dayPass1Jlabel = new JLabel("日普通(0)");
    public static JLabel dayPass2Jlabel = new JLabel("日困难(0)");
    public static JLabel dayPass5Jlabel = new JLabel("日地狱(0)");
    public static JLabel passPVPJlabel = new JLabel("PVP(0)");
    public static JLabel passTaskJlabel = new JLabel("场内任务(0)");

    public static JLabel pass1Jlabel = new JLabel("期普通(0)");
    public static JLabel pass2Jlabel = new JLabel("期困难(0)");
    public static JLabel pass5Jlabel = new JLabel("期地狱(0)");



    public static JTextField dhCodeField = new JTextField(10);
    public static JTextField uidField = new JTextField(10);


    //时间 2024-11-24 15:52:00
    public static JLabel currTimeJLabel = new JLabel("2024-11-24 15:52:00");


    //信息展示  fixme 如多线程频繁 setText JTextPanel组件 有可能会出现系统感叹号声音。所以建议用JLabel
    public static JLabel myFoodLabel = new JLabel();
    public static JLabel myLuckCoinLabel = new JLabel();
    public static JLabel myPopuLabel = new JLabel();

    public static JLabel waveLabel = new JLabel();
    public static JLabel timeLabel = new JLabel();
    public static JLabel monsterLabel = new JLabel();

    public static JLabel itFoodLabel = new JLabel();
    public static JLabel itLuckCoinLabel = new JLabel();
    public static JLabel itPopuLabel = new JLabel();


    public static JTextArea otherTextArea = new JTextArea();
    public static JTextArea myTextArea = new JTextArea();

    public static PlayPanel playPanel = new PlayPanel();

    //日志板子
    public static JTextArea consoleTextArea = new JTextArea();
    //聊天板子
    public static JPanel homeChatPanel = new JPanel(new GridBagLayout());
    public static JTextArea homeChatArea = new JTextArea();
    public static JTextArea fightChatArea = new JTextArea();

    public static JTextField homeChatInput = new JTextField();
    public static JTextField fightChatInput = new JTextField();
    //竞争和合作创建房间和加入房间
    public static JButton batCreateBtn = new JButton();
    public static JButton batFindRoomBtn = new JButton();
    public static JButton withCreateBtn = new JButton();
    public static JButton withFindRoomBtn = new JButton();
    public static JTextField batRoomField = new JTextField();
    public static JTextField withRoomField = new JTextField();

    //按钮
    public static JButton callBtn = new JButton();

    TcpClient tcpClient;

    @SneakyThrows
    public static void loadAccountSelect() {
        accountBox.removeAllItems();
        accountBox.addItem("新账号:1.左侧添加2.连接");
        accountBox.addItem("老帐号:1.此处选择2.连接");

        try {
            if (!Stores.localFile.exists()) {//文件为空，就先创建
                FileUtil.writeString(JSON.toJSONString(Stores.localDO), Stores.localFile, "UTF-8");//写文件
                log.info("创建文件:{}", Stores.localFile.getPath());//文件为空，就先创建
            }
//            log.info("读取文件:{},内容:{}", Stores.loginFile.getName(), fileStr);
            Stores.localDO = JSON.parseObject(FileUtil.readString(Stores.localFile, "UTF-8"), LocalDO.class);//文件赋值
            for (String key : Stores.localDO.getLoginMap().keySet()) {
                accountBox.addItem(key);
            }
        } catch (Exception e) {
            log.error("loadAccountSelect has Exception:{}", ThrowableUtil.stackTraceToString(e));
        } catch (Throwable e) {
            log.error("loadAccountSelect has Throwable:{}", ThrowableUtil.stackTraceToString(e));
        }
    }

    public static TrayIcon path2Icon(String trayIconPath){
        TrayIcon trayIcon;
        try {
            InputStream trayIs = WZDJMainFrame.class.getClassLoader().getResourceAsStream(trayIconPath);
            if (trayIs != null) {
                trayIcon = new TrayIcon(ImageIO.read(trayIs));
            } else {
                trayIcon = new TrayIcon(new ImageIcon(trayIconPath).getImage());
            }
        } catch (Exception e) {
            trayIcon = new TrayIcon(new ImageIcon(trayIconPath).getImage());
        }
        return trayIcon;
    }

    public WZDJMainFrame(TcpClient tcpClient) {
        try {
            this.tcpClient = tcpClient;
            setTitle("对决塔防(免责声明:仅用于学习,请勿滥用 wx[dahuo_yzs])");

//            TrayIcon trayIcon = path2Icon("img/qw.png");
//            setIconImage(trayIcon.getImage());

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setSize(screenSize.width, screenSize.height - 100);//全屏
            setLocationRelativeTo(null);//去除左上的定位，自动居中显示
            setLayout(new BorderLayout());
            //上方 1部分 二维码
            JPanel qrPanel = new JPanel(new BorderLayout());
            qrPanel.setBorder(BorderFactory.createTitledBorder("添加wx账号"));
            qrCanvas.setPreferredSize(new Dimension(100, 100));
            qrCanvas.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    refreshQR();//窗口点击事件
                }
            });
//            refreshQR();//初始化时，刷新二维码
            byte[] bytes = ResourceUtil.readBytes("img/touch_blue.png");
            BufferedImage qrImg = ImageIO.read(new ByteArrayInputStream(bytes));
            qrCanvas.drawInit(qrImg, "点击获取二维码");
            qrPanel.add(qrCanvas, BorderLayout.CENTER);


            //添加APP账号
            JPanel accountPanel = new JPanel(new GridBagLayout());
            accountPanel.setBorder(BorderFactory.createTitledBorder("添加APP账号"));
            GridBagConstraints accountGbc = new GridBagConstraints();
            accountGbc.insets = new Insets(0, 0, 0, 0);
            accountGbc.gridwidth = 1;
            accountGbc.gridy = 0;
            accountGbc.gridx = 0;
            accountPanel.add(accountJTF, accountGbc);
            accountGbc.gridy++;
            accountPanel.add(passwordJTF, accountGbc);
            accountGbc.gridy++;
            JButton accountLoginBtn = new JButton("添加APP账号");
            accountLoginBtn.addActionListener(e -> handleAccountLoginClick());
            accountPanel.add(accountLoginBtn, accountGbc);
            accountGbc.gridy++;


            //连接服务器
            JPanel serverPanel = new JPanel(new GridBagLayout());
            serverPanel.setBorder(BorderFactory.createTitledBorder("连接服务器"));
            GridBagConstraints serverGbc = new GridBagConstraints();
            serverGbc.insets = new Insets(0, 0, 0, 0);
            serverGbc.gridwidth = 1;
            serverGbc.gridy = 0;
            serverGbc.gridx = 0;
            serverPanel.add(qrStatusLabel, serverGbc);
            serverGbc.gridy++;
            accountBox = new JComboBox<>();
            loadAccountSelect();
            serverPanel.add(accountBox, serverGbc);
            serverGbc.gridy++;
            JButton connectButton = new JButton("连接服务器");
            connectButton.addActionListener(e -> handleConnClick());
            serverPanel.add(connectButton, serverGbc);
            serverGbc.gridy++;
            modelBox = new JComboBox<>();
            modelBox.addItem("正常 手动游戏");
            modelBox.addItem("挂机 合作清体");
//            modelBox.addItem("挂机 竞技匹配");
//            modelBox.addItem("挂机 自动(合作|竞技)");
            modelBox.addActionListener(e -> handleModelSelect());
            serverPanel.add(modelBox, serverGbc);



            JPanel itemJPanel = new JPanel(new GridBagLayout());
            itemJPanel.setBorder(BorderFactory.createTitledBorder("道具信息"));
            GridBagConstraints p3itemGbc = new GridBagConstraints();
            p3itemGbc.insets = new Insets(0, 0, 0, 0);
            p3itemGbc.gridwidth = 1;
            p3itemGbc.gridy = 0;
            p3itemGbc.gridx = 0;
            itemJPanel.add(goldJlabel, p3itemGbc);
            p3itemGbc.gridx++;
            itemJPanel.add(diamondJlabel, p3itemGbc);
            p3itemGbc.gridy = 1;
            p3itemGbc.gridx = 0;
            itemJPanel.add(mythicStoneJlabel, p3itemGbc);
            p3itemGbc.gridx++;
            itemJPanel.add(mineKeyJlabel, p3itemGbc);
            p3itemGbc.gridy = 2;
            p3itemGbc.gridx = 0;
            itemJPanel.add(recruitKeyJlabel, p3itemGbc);
            p3itemGbc.gridx++;
            itemJPanel.add(recruitGemJlabel, p3itemGbc);

            p3itemGbc.gridy = 3;
            p3itemGbc.gridx = 0;
            itemJPanel.add(energyJlabel, p3itemGbc);
            p3itemGbc.gridx++;
            itemJPanel.add(energyNextJlabel, p3itemGbc);


            //p4 商店
            shopRefreshBtn.addActionListener(e -> handleShopRefreshClick());
            goodLabels.add(goodLabel2);
            goodLabels.add(goodLabel3);
            goodLabels.add(goodLabel4);
            goodLabels.add(goodLabel5);
            goodLabels.add(goodLabel6);
            goodLabels.add(goodLabel7);

            for (int i = 0; i < goodLabels.size(); i++) {
                final int  finalI = i;
                JLabel jLabel = goodLabels.get(i);
                jLabel.addMouseListener(new MouseAdapter(){
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        GoodsVO goodsVO = Stores.getInstance().getGoodsVOMap().get(finalI);
                        if (jLabel.getText().endsWith("1")) {
                            log.info("下标:" + finalI + " 购买");
                            WZDJSender.rpcServerShopBuy(goodsVO.getShopId(), goodsVO.getGoodsId());//金币兑换商店买按钮被点击遍历兑换
                        } else {
                            log.info("下标:" + finalI + " 请勿重复购买");
                        }
                    }
                });
            }

            JPanel shopJPanel = new JPanel(new GridBagLayout());
            shopJPanel.setBorder(BorderFactory.createTitledBorder("商店信息"));
            GridBagConstraints p4shopGbc = new GridBagConstraints();
            p4shopGbc.insets = new Insets(0, 0, 0, 0);
            p4shopGbc.gridwidth = 1;
            p4shopGbc.gridy = 0;
            p4shopGbc.gridx = 0;
            shopJPanel.add(shopRefreshBtn, p4shopGbc);
            p4shopGbc.gridx++;
            JButton buyGoldGoodsBtn = new JButton("买");
            buyGoldGoodsBtn.addActionListener(e -> handleBuyGoldGoodsClick());
            shopJPanel.add(buyGoldGoodsBtn, p4shopGbc);
            p4shopGbc.gridx++;

            shopJPanel.add(goodLabel7, p4shopGbc);

            p4shopGbc.gridy = 1;
            p4shopGbc.gridx = 0;
            shopJPanel.add(goodLabel2, p4shopGbc);
            p4shopGbc.gridx++;
            shopJPanel.add(goodLabel3, p4shopGbc);
            p4shopGbc.gridx++;
            shopJPanel.add(goodLabel4, p4shopGbc);
            p4shopGbc.gridy = 2;
            p4shopGbc.gridx = 0;
            shopJPanel.add(goodLabel5, p4shopGbc);
            p4shopGbc.gridx++;
            shopJPanel.add(goodLabel6, p4shopGbc);
            p4shopGbc.gridx++;


            //通关奖励情况
            JPanel passRewardJPanel = new JPanel(new GridBagLayout());
            passRewardJPanel.setBorder(BorderFactory.createTitledBorder("通关奖励"));
            GridBagConstraints passRewardGbc = new GridBagConstraints();
            passRewardGbc.insets = new Insets(0, 0, 0, 0);
            passRewardGbc.gridwidth = 1;
            passRewardGbc.gridy = 0;
            passRewardGbc.gridx = 0;


            passRewardJPanel.add(dayPass1Jlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(dayPass2Jlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(dayPass5Jlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(passPVPJlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(passTaskJlabel,passRewardGbc);
            passRewardGbc.gridy=0;
            passRewardGbc.gridx++;
            passRewardJPanel.add(pass1Jlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(pass2Jlabel,passRewardGbc);
            passRewardGbc.gridy++;
            passRewardJPanel.add(pass5Jlabel,passRewardGbc);
            passRewardGbc.gridy++;


            //兑换
            JPanel anyJPanel = new JPanel(new GridBagLayout());
            anyJPanel.setBorder(BorderFactory.createTitledBorder("兑换-用户查询-好友"));
            GridBagConstraints anyGbc = new GridBagConstraints();
            anyGbc.insets = new Insets(0, 0, 0, 0);
            anyGbc.gridy = 0;
            anyGbc.gridx = 0;

            //兑换输入框
            anyJPanel.add(dhCodeField, anyGbc);
            anyGbc.gridx++;
            //兑换按钮
            JButton dhCodeBtn = new JButton("兑换码");
            dhCodeBtn.addActionListener(e -> handleDHClick());
            anyJPanel.add(dhCodeBtn, anyGbc);
            anyGbc.gridx++;
            JButton getDhCodeBtn = new JButton("获取码");
            getDhCodeBtn.addActionListener(e -> handleGetDHClick());
            anyJPanel.add(getDhCodeBtn, anyGbc);
            anyGbc.gridy++;
            anyGbc.gridx = 0;

            //用户 uid 输入框
            anyJPanel.add(uidField,anyGbc);
            anyGbc.gridx++;
            //用户查询按钮
            JButton userViewBtn = new JButton("查用户");
            userViewBtn.addActionListener(e -> handleUserViewClick());
            anyJPanel.add(userViewBtn,anyGbc);
            anyGbc.gridx++;
            JButton userAddBtn = new JButton("加好友");
            userAddBtn.addActionListener(e -> handleUserAddClick());
            anyJPanel.add(userAddBtn,anyGbc);
            anyGbc.gridy++;
            anyGbc.gridx = 0;

            JButton friendsBtn = new JButton("好友列表");
            friendsBtn.addActionListener(e -> {WZDJService.showFriends();});
            anyJPanel.add(friendsBtn,anyGbc);
            anyGbc.gridx++;
            JButton friendDelBtn = new JButton("清30天离线好友");
            friendDelBtn.addActionListener(e -> {WZDJService.clearFriendsByMonth();});
            anyJPanel.add(friendDelBtn,anyGbc);
            anyGbc.gridy++;
            anyGbc.gridx = 0;
            //当前时间
            currTimeJLabel.setForeground(Color.RED);
            anyJPanel.add(currTimeJLabel,anyGbc);
            anyGbc.gridx++;

            //顶部左侧布局
            JPanel topLeftPanel = new JPanel(new GridBagLayout());
            GridBagConstraints topGbc = new GridBagConstraints();
            topGbc.gridwidth = 1;
            topGbc.gridy = 0;
            topGbc.gridx = 0;
//            topLeftPanel.add(qrPanel, topGbc);
//            topGbc.gridx++;
            topLeftPanel.add(accountPanel, topGbc);
            topGbc.gridx++;
            topLeftPanel.add(serverPanel, topGbc);
            topGbc.gridx++;
            topLeftPanel.add(itemJPanel, topGbc);
            topGbc.gridx++;
            topLeftPanel.add(shopJPanel, topGbc);
            topGbc.gridx++;
            topLeftPanel.add(passRewardJPanel, topGbc);
            topGbc.gridx++;
            topLeftPanel.add(anyJPanel, topGbc);
            topGbc.gridx++;

            //中间  打赏，时间
            JPanel topCenterPanel = new JPanel(new BorderLayout());
//            topCenterPanel.setBackground(Color.WHITE);
//            topCenterPanel.setBorder(BorderFactory.createTitledBorder(""));


//            JPanel dsJpanel = new JPanel();
            dsCanvas.setPreferredSize(new Dimension(100, 100));
            byte[] dsImgBytes = ResourceUtil.readBytes("img/ds.png");
            BufferedImage dsImg = ImageIO.read(new ByteArrayInputStream(dsImgBytes));
            dsCanvas.drawImg(dsImg);
            dsJpanel.add(dsCanvas);
            dsJpanel.setBorder(BorderFactory.createTitledBorder("非强制打赏"));
            dsJpanel.setVisible(false);
            topCenterPanel.add(dsJpanel, BorderLayout.WEST);





            //右边
//            JPanel topRightPanel = new JPanel(new BorderLayout());
////            topRightPanel.setBackground(Color.WHITE);
//            topRightPanel.setBorder(BorderFactory.createTitledBorder("当前时间"));
//            currTimeJLabel.setFont(new Font("宋体", Font.BOLD, 24));
//            currTimeJLabel.setForeground(Color.RED);
//            topRightPanel.add(currTimeJLabel, BorderLayout.CENTER);


            //上方左中右布局
            JPanel topPanel = new JPanel(new BorderLayout());
            topPanel.add(topLeftPanel, BorderLayout.WEST);
            topPanel.add(topCenterPanel, BorderLayout.CENTER);
//            topPanel.add(topRightPanel, BorderLayout.EAST);
            //上方整理布局
            add(topPanel, BorderLayout.NORTH);
            //中间部分   左侧敌我信息，中间游戏，右侧日志
            JPanel centerPanel = new JPanel();

            //中间左侧板 队友和自己的战斗信息
            JPanel infoPanel = new JPanel(new BorderLayout());
            otherTextArea = new JTextArea(8, 30);//高，宽
            otherTextArea.setLineWrap(false); // 不自动换行
            otherTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); // 使用等宽字体
            otherTextArea.setEditable(false); // 文本区域不可编辑
            JScrollPane otherScrollPane = new JScrollPane(otherTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            otherScrollPane.setBorder(BorderFactory.createTitledBorder("队友信息"));
            myTextArea = new JTextArea(8, 30);//高，宽
            myTextArea.setLineWrap(false); // 不自动换行
            myTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); // 使用等宽字体
            myTextArea.setEditable(false); // 文本区域不可编辑
            JScrollPane myScrollPane = new JScrollPane(myTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            myScrollPane.setBorder(BorderFactory.createTitledBorder("我的信息"));
            infoPanel.add(otherScrollPane, BorderLayout.NORTH);
            infoPanel.add(myScrollPane, BorderLayout.CENTER);

            //游戏区域 上方信息
            JPanel gameInfoPanel = new JPanel(new GridBagLayout());
            GridBagConstraints gameUpGbc = new GridBagConstraints();
            gameUpGbc.insets = new Insets(0, 10, 0, 10);
            gameUpGbc.gridwidth = 1;
            gameUpGbc.gridy = 0;
            gameUpGbc.gridx = 0;
            myFoodLabel.setText("食物:0");//初始化默认为0
            gameInfoPanel.add(myFoodLabel, gameUpGbc);
            gameUpGbc.gridx++;
            myLuckCoinLabel.setText("幸运:0");//初始化默认为0
            gameInfoPanel.add(myLuckCoinLabel, gameUpGbc);
            gameUpGbc.gridx++;
            myPopuLabel.setText("英雄:0/20");//初始化默认为0
            gameInfoPanel.add(myPopuLabel, gameUpGbc);
            //中间
            gameUpGbc.gridx++;
            waveLabel.setText("回合:0");//初始化默认为0
            gameInfoPanel.add(waveLabel, gameUpGbc);
            gameUpGbc.gridx++;
            timeLabel.setText("00:00");//初始化默认为0
            gameInfoPanel.add(timeLabel, gameUpGbc);
            gameUpGbc.gridx++;
            monsterLabel.setText("怪:0/100");//初始化默认为0
            gameInfoPanel.add(monsterLabel, gameUpGbc);

            gameUpGbc.gridx++;
            itFoodLabel.setText("it食物:0");//初始化默认为0
            gameInfoPanel.add(itFoodLabel, gameUpGbc);
            gameUpGbc.gridx++;
            itLuckCoinLabel.setText("it幸运:0");//初始化默认为0
            gameInfoPanel.add(itLuckCoinLabel, gameUpGbc);
            gameUpGbc.gridx++;
            itPopuLabel.setText("it英雄:0/20");//初始化默认为0
            gameInfoPanel.add(itPopuLabel, gameUpGbc);


            //游戏区
            playPanel = new PlayPanel();

            //强化区
            JPanel enhancePanel = new JPanel(new GridBagLayout());
            GridBagConstraints enhanceGbc = new GridBagConstraints();
            enhanceGbc.insets = new Insets(0, 10, 0, 10);
            enhanceGbc.gridwidth = 1;
            enhanceGbc.gridy = 0;
            enhanceGbc.gridx = 0;
            enhancePanel.add(callCostJlabel, gameUpGbc);
            gameUpGbc.gridx++;
            enhancePanel.add(enhance1Jlabel, gameUpGbc);
            gameUpGbc.gridx++;
            enhancePanel.add(enhance2Jlabel, gameUpGbc);
            gameUpGbc.gridx++;
            enhancePanel.add(enhance3Jlabel, gameUpGbc);
            gameUpGbc.gridx++;
            enhancePanel.add(enhance4Jlabel, gameUpGbc);
            gameUpGbc.gridx++;

            //游戏区域布局分布
            JPanel gamePanel = new JPanel(new BorderLayout());
            gamePanel.add(gameInfoPanel, BorderLayout.NORTH);//游戏区域 上方 战斗信息
            gamePanel.add(playPanel, BorderLayout.CENTER);//游戏区域 中间 游玩区
            gamePanel.add(enhancePanel, BorderLayout.SOUTH);//游戏区域 下方 强化信息
            gamePanel.setPreferredSize(new Dimension(700, 400));
            gamePanel.setBorder(BorderFactory.createTitledBorder("游戏区域(左键组合,拖拽移动,右键删除)"));

            // 控制台文本区域
            consoleTextArea = new JTextArea(18, 65);//高，宽
            consoleTextArea.setLineWrap(false); // 不自动换行
            consoleTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); // 使用等宽字体
            consoleTextArea.setEditable(false); // 文本区域不可编辑
            JScrollPane consoleScrollPane = new JScrollPane(consoleTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            consoleScrollPane.setBorder(BorderFactory.createTitledBorder("日志台"));
            //布局
            centerPanel.add(infoPanel, BorderLayout.EAST);
            centerPanel.add(gamePanel, BorderLayout.CENTER);
            centerPanel.add(consoleScrollPane, BorderLayout.WEST);
            add(centerPanel, BorderLayout.CENTER);


            //底部三分部 左中右
            homeChatPanel = new JPanel(new GridBagLayout());
            homeChatPanel.setBorder(BorderFactory.createTitledBorder("大厅聊天"));
            GridBagConstraints homeChatGbc = new GridBagConstraints();
            homeChatGbc.insets = new Insets(5, 5, 5, 5);
            homeChatGbc.gridwidth = 5; // 每个占一列
            homeChatGbc.gridy = 0;
            homeChatGbc.gridx = 0;
            homeChatArea = new JTextArea(13, 60);//高，宽
            homeChatArea.setLineWrap(false); // 不自动换行
            homeChatArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); // 使用等宽字体
            homeChatArea.setEditable(false); // 文本区域不可编辑
            JScrollPane homeChatScroll = new JScrollPane(homeChatArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            homeChatPanel.add(homeChatScroll, homeChatGbc);
            homeChatGbc.gridwidth = 1; // 每个占一列
            homeChatGbc.gridy = 1;
            homeChatGbc.gridx = 0;
            homeChatInput = new JTextField(20);
            homeChatPanel.add(homeChatInput, homeChatGbc);
            homeChatInput.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    super.keyPressed(e);
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        handleHomeChatClick();
                    }
                }
            });
            homeChatGbc.gridx = 1;
            JButton homeChatSendBtn = new JButton("大厅聊天");
            homeChatSendBtn.addActionListener(e -> handleHomeChatClick());
            homeChatPanel.add(homeChatSendBtn, homeChatGbc);
            homeChatGbc.gridx = 2;
            JCheckBox homeAutoChatBox = new JCheckBox("20定频");
            homeAutoChatBox.setSelected(Stores.getInstance().isHomeAutoChat());
            homeAutoChatBox.addActionListener(e -> handleHomeAutoChatClick());
            homeChatPanel.add(homeAutoChatBox, homeChatGbc);
            //下部分部分：按钮
            JPanel buttonPanel = new JPanel(new GridBagLayout());
            GridBagConstraints btnGbc = new GridBagConstraints();
            btnGbc.insets = new Insets(5, 5, 5, 5); // 设置按钮周围的间距
            btnGbc.fill = GridBagConstraints.HORIZONTAL; // 按钮水平填充
            // 第1行：一键领奖和清屏
            btnGbc.gridwidth = 1; // 每个占一列
            btnGbc.gridy = 0;
            btnGbc.gridx = 0;

            JButton gianAwardBtn = new JButton("一键领奖");
            gianAwardBtn.addActionListener(e -> handleGainAwardClick());
            buttonPanel.add(gianAwardBtn, btnGbc);
            btnGbc.gridx++;
            JButton clearBtn = new JButton("清屏");
            clearBtn.addActionListener(e -> handleClearClick());
            buttonPanel.add(clearBtn, btnGbc);
            btnGbc.gridx++;
            JButton recruitBtn1 = new JButton("招募1");
            recruitBtn1.addActionListener(e -> handlerRecruitClick(1));
            buttonPanel.add(recruitBtn1, btnGbc);
            btnGbc.gridx++;
            JButton recruitBtn2 = new JButton("招募10");
            recruitBtn2.addActionListener(e -> handlerRecruitClick(10));
            buttonPanel.add(recruitBtn2, btnGbc);


            // 第2行：竞技模式
            btnGbc.gridwidth = 1; // 每个占一列
            btnGbc.gridy = 1;
            btnGbc.gridx = 0;
            JButton batMatchBtn = new JButton("竞技匹配");
            batMatchBtn.addActionListener(e -> handleBatMatchClick());
            buttonPanel.add(batMatchBtn, btnGbc);
            btnGbc.gridx++;
            batCreateBtn = new JButton("竞技创建");
            batCreateBtn.addActionListener(e -> handleBatCreateClick());
            buttonPanel.add(batCreateBtn, btnGbc);
            btnGbc.gridx++;
            batRoomField = new JTextField(5); // 假设宽度为20列
            buttonPanel.add(batRoomField, btnGbc);
            btnGbc.gridx++;
            JButton batJoinBtn = new JButton("竞技加入");
            batJoinBtn.addActionListener(e -> handleBatJoinClick());
            buttonPanel.add(batJoinBtn, btnGbc);
            btnGbc.gridx++;
//            batFindRoomBtn = new JButton("竞技找房");
//            batFindRoomBtn.addActionListener(e -> handleBatFindClick());
//            buttonPanel.add(batFindRoomBtn, btnGbc);

            // 第3行：合作模式
            btnGbc.gridwidth = 1; // 每个占一列
            btnGbc.gridy = 2;
            btnGbc.gridx = 0;
            JButton withMatchButton = new JButton("合作匹配");
            withMatchButton.addActionListener(e -> handleWithMatchBtnClick());
            buttonPanel.add(withMatchButton, btnGbc);
            btnGbc.gridx++;
            withCreateBtn = new JButton("合作创建");
            withCreateBtn.addActionListener(e -> handleWithCreateClick());
            buttonPanel.add(withCreateBtn, btnGbc);
            btnGbc.gridx++;
            withRoomField = new JTextField(5); // 假设宽度为20列
            buttonPanel.add(withRoomField, btnGbc);
            btnGbc.gridx++;
            JButton withJoinBtn = new JButton("合作加入");
            withJoinBtn.addActionListener(e -> handleWithJoinClick());
            buttonPanel.add(withJoinBtn, btnGbc);
            btnGbc.gridx++;
//            withFindRoomBtn = new JButton("合作找房");
//            withFindRoomBtn.addActionListener(e -> handleWithFindClick());
//            buttonPanel.add(withFindRoomBtn, btnGbc);

            // 第4行：召唤和挑战副本
            btnGbc.gridwidth = 1; // 每个占一列
            btnGbc.gridy = 3;
            btnGbc.gridx = 0;
            callBtn = new JButton("召唤");
            callBtn.addActionListener(e -> handleCallBtnClick());
            buttonPanel.add(callBtn, btnGbc);
            btnGbc.gridx++;
            JButton challengeDungeonBtn = new JButton("狩猎");
            challengeDungeonBtn.addActionListener(e -> handleChallengeClick());
            buttonPanel.add(challengeDungeonBtn, btnGbc);
            btnGbc.gridx++;

            buttonPanel.setBorder(BorderFactory.createTitledBorder("操作按钮"));


            // 第5行：三个赌博按钮（这里假设为“赌博1”，“赌博2”，“赌博3”）
            btnGbc.gridwidth = 1; // 每个占一列
            btnGbc.gridy = 4;
            btnGbc.gridx = 0;
            for (int i = 1; i <= 3; i++) {
                JButton gambleButton = new JButton("赌博" + i);
                buttonPanel.add(gambleButton, btnGbc);
                int finalI = i;
                gambleButton.addActionListener(e -> handleGambleButtonClick(finalI));
                btnGbc.gridx++; // 移动到下一列
            }
            JButton btn1 = new JButton("耗时");
            btn1.addActionListener(e -> handlerBtnClick(1));
//            buttonPanel.add(btn1, btnGbc);
            btnGbc.gridx++;
            JButton btn2 = new JButton("耗时reset");
            btn2.addActionListener(e -> handlerBtnClick(2));
//            buttonPanel.add(btn2, btnGbc);

            // 第五行：四个强化按钮
            btnGbc.gridwidth = 1; // 每个强化按钮占一列
            btnGbc.gridy = 5;
            btnGbc.gridx = 0;
            for (int i = 1; i <= 4; i++) {
                JButton enhanceButton = new JButton("强化" + i);
                buttonPanel.add(enhanceButton, btnGbc);
                int finalI = i;
                enhanceButton.addActionListener(e -> handleEnhanceButtonClick(finalI));
                btnGbc.gridx++; // 移动到下一列
            }

            // 第6行：5个测试按钮
            btnGbc.gridwidth = 1; // 每个测试按钮占一列
            btnGbc.gridy = 6;
            btnGbc.gridx = 0;

            JCheckBox autoEightCall = new JCheckBox("自动召唤");
            autoEightCall.setSelected(Stores.getInstance().isAutoCall());
            buttonPanel.add(autoEightCall, btnGbc);
            autoEightCall.addActionListener(e -> handleTestBtnClick(1));
            btnGbc.gridx++;

            JCheckBox autoComb = new JCheckBox("自动3合1");
            autoComb.setSelected(Stores.getInstance().isAutoCombination());
            buttonPanel.add(autoComb, btnGbc);
            autoComb.addActionListener(e -> handleTestBtnClick(2));
            btnGbc.gridx++;

            JCheckBox autoMy = new JCheckBox("自动合神话");
            autoMy.setSelected(Stores.getInstance().isAutoMythic());
            buttonPanel.add(autoMy, btnGbc);
            autoMy.addActionListener(e -> handleTestBtnClick(3));
            btnGbc.gridx++;

            JCheckBox autoMove = new JCheckBox("自动移动");
            autoMove.setSelected(Stores.getInstance().isAutoMove());
            buttonPanel.add(autoMove, btnGbc);
            autoMove.addActionListener(e -> handleTestBtnClick(4));
            btnGbc.gridx++;

            JCheckBox autoRemove = new JCheckBox("自动删低级");
            autoRemove.setSelected(Stores.getInstance().isAutoRemove());
            buttonPanel.add(autoRemove, btnGbc);
            autoRemove.addActionListener(e -> handleTestBtnClick(5));
            btnGbc.gridy++;
            btnGbc.gridx = 0;
            JCheckBox autoGambling = new JCheckBox("自动赌博紫");
            autoGambling.setSelected(Stores.getInstance().isAutoGambling());
            buttonPanel.add(autoGambling, btnGbc);
            autoGambling.addActionListener(e -> handleTestBtnClick(6));
            btnGbc.gridx++;
            JCheckBox autoStrengthen = new JCheckBox("自动强化");
            autoStrengthen.setSelected(Stores.getInstance().isAutoStrengthen());
            buttonPanel.add(autoStrengthen, btnGbc);
            autoStrengthen.addActionListener(e -> handleTestBtnClick(7));
            btnGbc.gridx++;
            JCheckBox autoHunting = new JCheckBox("自动狩猎");
            autoHunting.setSelected(Stores.getInstance().isAutoHunting());
            buttonPanel.add(autoHunting, btnGbc);
            autoHunting.addActionListener(e -> handleTestBtnClick(8));
            btnGbc.gridx++;

            //此功能不可用
//            JCheckBox accelerate = new JCheckBox("加速");
//            accelerate.setSelected(Stores.getInstance().isAccelerate());
//            buttonPanel.add(accelerate, btnGbc);
//            accelerate.addActionListener(e -> handleTestBtnClick(9));
//            btnGbc.gridx++;


            JPanel fightChatPanel = new JPanel(new GridBagLayout());
            fightChatPanel.setBorder(BorderFactory.createTitledBorder("局内聊天"));
            GridBagConstraints fightGbc = new GridBagConstraints();
            fightGbc.insets = new Insets(5, 5, 5, 5);
            fightGbc.gridwidth = 5; // 每个测试按钮占一列
            fightGbc.gridy = 0;
            fightGbc.gridx = 0;
            fightChatArea = new JTextArea(13, 60);//高，宽
            fightChatArea.setLineWrap(false); // 不自动换行
            fightChatArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); // 使用等宽字体
            fightChatArea.setEditable(true); // 文本区域不可编辑
            JScrollPane fightChatScroll = new JScrollPane(fightChatArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            fightChatPanel.add(fightChatScroll, fightGbc);
            fightGbc.gridwidth = 1; // 每个测试按钮占一列
            fightGbc.gridy = 1;
            fightGbc.gridx = 0;
            fightChatInput = new JTextField(20);
            fightChatPanel.add(fightChatInput, fightGbc);
            fightChatInput.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    super.keyPressed(e);
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        handleFightChatClick();
                    }
                }
            });
            fightGbc.gridx++;
            JButton fightChatSendBtn = new JButton("局内聊天");
            fightChatSendBtn.addActionListener(e -> handleFightChatClick());
            fightChatPanel.add(fightChatSendBtn, fightGbc);
            fightGbc.gridx++;
            JCheckBox replayBox = new JCheckBox("回复");
            replayBox.setSelected(Stores.getInstance().isFightReplayChat());
            replayBox.addActionListener(e -> handleFightAutoReplayClick());
            fightChatPanel.add(replayBox, fightGbc);
            fightGbc.gridx++;
//            JCheckBox waveTipsBox = new JCheckBox("关卡");
//            waveTipsBox.setSelected(Stores.getInstance().isFightWaveChat());
//            waveTipsBox.addActionListener(e -> handleFightAutoWaveClick());
//            fightChatPanel.add(waveTipsBox, fightGbc);

            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(homeChatPanel, BorderLayout.WEST);
            bottomPanel.add(buttonPanel, BorderLayout.CENTER);
            bottomPanel.add(fightChatPanel, BorderLayout.EAST);
            add(bottomPanel, BorderLayout.SOUTH);

            setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 事件处理程序方法（根据需要实现）
    @SneakyThrows
    public static void refreshQR() {
        long start = System.currentTimeMillis();
        WxGetQrRes wxGetQrRes = WxApi.getQR();
        log.info("getQR耗时:" + (System.currentTimeMillis() - start));
        if (wxGetQrRes == null) {//获取二维码失败
            JOptionPane.showMessageDialog(null, "获取二维码失败，可能存在网络问题请联系qq835476090");
            return;
        }
        long base64Start = System.currentTimeMillis();
        String qrBase64 = wxGetQrRes.getQrBase64();
        qrBase64 = qrBase64.replace("data:image/png;base64,", "").replace("data:image/jpg;base64,", "");
        byte[] decode = Base64.getDecoder().decode(qrBase64);
        ByteArrayInputStream bis = new ByteArrayInputStream(decode);
        BufferedImage image1 = ImageIO.read(bis);
        log.info("image1耗时:" + (System.currentTimeMillis() - base64Start));
        //这个去URL再下载要4-5秒 不推荐用url
//        long urlStart = System.currentTimeMillis();
//        URL url = new URL(wxQrRes.getQrUrl());
//        BufferedImage image2 = ImageIO.read(url);
//        log.info("image2耗时:" + (System.currentTimeMillis() - urlStart));
        qrCanvas.drawImg(image1);//点击二维码框刷新
    }


    public void handleConnClick() {
        this.tcpClient.connect("127.0.0.1", 8080);//这里获取WZDJ那里获取ip和端口此处不处理
    }

    public void handleAccountLoginClick() {
        String account = accountJTF.getText();
        String password = passwordJTF.getText();
        if (StrUtil.isBlank(account) || StrUtil.isBlank(password)) {
            JOptionPane.showMessageDialog(null, "账号|密码 不能为空");
            return;
        }
        log.info("{}account:{},password:{}", Console.where(), account, password);
        Stores.getInstance().setAccount(account);//APP登录 账号添加按钮被点击
        Stores.getInstance().setPassword(password);//APP登录 账号添加按钮被点击
        Stores.getInstance().setLoginType(Consts.LOGIN_TYPE_APP);//APP登录

        HttpLoginResult httpLoginResult = WZDJAppSign.loginByAccount(account, password);
        if (httpLoginResult != null && httpLoginResult.getResult() != null) {
//            String selectItemStr = account + "_APP";
            String selectItemStr = Consts.LOGIN_TYPE_APP + account;
            WZDJLocalItem wzdjLocalItem = Stores.localDO.getLoginMap().getOrDefault(selectItemStr, new WZDJLocalItem());
            wzdjLocalItem.setLoginType(Consts.LOGIN_TYPE_APP);
            wzdjLocalItem.setItemSelectStr(selectItemStr);//key更新
            wzdjLocalItem.setHttpLoginResult(httpLoginResult);
            AppAccountInfo appAccountInfo = new AppAccountInfo();
            appAccountInfo.setAccount(account);
            appAccountInfo.setPassword(password);
            wzdjLocalItem.setAppAccountInfo(appAccountInfo);
            wzdjLocalItem.setToken2GameUser(WZDJSign.decodeObj(httpLoginResult.getResult().getAccessToken()));

            Stores.localDO.getLoginMap().put(selectItemStr, wzdjLocalItem);//回写内存数据
            //回写磁盘
            FileUtil.writeString(JSONUtil.toJsonPrettyStr(Stores.localDO), Stores.localFile, "UTF-8");//回写磁盘
            //选项卡更新
            WZDJMainFrame.accountBox.addItem(selectItemStr);
            WZDJMainFrame.accountBox.setSelectedItem(selectItemStr);
            String accessToken = wzdjLocalItem.getHttpLoginResult().getResult().getAccessToken();
            AuthRes authRes = AuthUtil.auth(accessToken, wzdjLocalItem.getToken2GameUser().getUserId(), wzdjLocalItem.getToken2GameUser().getOpenId());
            if (authRes != null && authRes.getUserdInfo() != null) {
                //登录成功的用户信息存储
                Stores.getInstance().setUserInfo(authRes.getUserdInfo());
                Stores.getInstance().setSelectItemStr(selectItemStr);
                Stores.getInstance().setWzdjLocalItem(wzdjLocalItem);
                log.info("2.缓存账号信息 登录成功");
            }else {
                log.info("2.缓存账号信息 登录失败，下一步 手动登录了");
            }
        } else {
            log.error("2.缓存账号信息 登录失败，下一步 手动登录了 result:{}",httpLoginResult);
        }
    }

    private void handleModelSelect() {
        int selectIndex = modelBox.getSelectedIndex();
        log.info("模式切换:{}", selectIndex);
        Stores.getInstance().getModel().set(selectIndex);
    }


    //兑换
    private void handleDHClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        String text = dhCodeField.getText().trim();
        if (StrUtil.isNotBlank(text)) {
            WZDJSender.rpcServerUserActivationCode(text);
        }
    }

    //获取兑换码
    private void handleGetDHClick() {
        StringBuilder sb = new StringBuilder("可尝试下方兑换码.领取奖励\n");
        for (String s : Stores.getInstance().dhWzdjCfg.getDhCodeList()) {
            sb.append(s).append("\n");
        }
        WZDJMainFrame.consoleTextArea.append(sb.toString());
    }

    //用户信息查询
    private void handleUserViewClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        String text = uidField.getText().trim();
        if (StrUtil.isNotBlank(text) && NumberUtil.isNumber(text)) {
            Integer uid = Convert.toInt(text);
            WZDJSender.rpcServerUserView(uid);
            WZDJSender.rpcServerFriendFightInvite(uid, 2);//请求合作模式
        }
    }

    //添加好友
    private void handleUserAddClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        String text = uidField.getText().trim();
        if (StrUtil.isNotBlank(text) && NumberUtil.isNumber(text)) {
            Integer uid = Convert.toInt(text);
            WZDJSender.rpcServerFriendApplyAdd(uid);
        }
    }

    //大厅聊天
    private void handleHomeChatClick() {
        String text = homeChatInput.getText();
        if (StrUtil.isNotBlank(text)) {//大厅发送聊天
            WZDJSender.rpcServerChatSend(text, 1);//大厅聊天
        }
    }

    private void handleHomeAutoChatClick() {
        Stores.getInstance().setHomeAutoChat(!Stores.getInstance().isHomeAutoChat());
        log.info("定频发送:" + Stores.getInstance().isHomeAutoChat());
    }

    private void handleFightChatClick() {
        String text = fightChatInput.getText();
        if (StrUtil.isNotBlank(text)) {//局内发送聊天
            WZDJSender.rpcServerChatSend(text, 6);//局内聊天
        }
    }

    private void handleFightAutoReplayClick() {
        Stores.getInstance().setFightReplayChat(!Stores.getInstance().isFightReplayChat());
        log.info("自动回复:" + Stores.getInstance().isFightReplayChat());
    }

    //是否开启 关卡 播报
    private void handleFightAutoWaveClick() {
        Stores.getInstance().setFightWaveChat(!Stores.getInstance().isFightWaveChat());
        log.info("关卡提示:" + Stores.getInstance().isFightWaveChat());
    }

    public void handleGainAwardClick() {
        String time = DateUtil.formatDateTime(new Date());
        String text = time + "一键领奖";
        log.info(text);
        WZDJMainFrame.consoleTextArea.append(text+"\n");
        //领取每日签到奖励
        gainDaySignAward();
        //领取每日商品奖励
        gainDayGoodsAward();//一键领奖 ，领取免费的商品
        //10001金币商店 购买值得买的商品
        goldBuyGoods();//10001金币商店 购买值得买的商品
        //领取通行证奖励
        gainPassportInfoLevelAward();
        //领取舞台达成奖励
        gainStageOkAward();
        //领取限时英雄20个卷轴免费礼包
        gainLimitShopDailyGift();
        //领取每日探索任务奖励
        gainDayTaskAward();
        //每日钻石兑换高级卷和锤子
        gainDiamondExchange();
    }

    //每日钻石兑换高级卷和锤子
    public void gainDiamondExchange() {
        WZDJSender.rpcServerShopBuy(31001, 1);//100个钻石购买一个高级卷+20普通卷
        WZDJSender.rpcServerShopBuy(32001, 1);//100个钻石1个锤子+1000个金币
    }


    //每日签到奖励
    private void gainDaySignAward() {
        //条件领取
        WZDJPack wzdjPack = WZDJCaller.getResCacheMap().get(1900549);
        if (wzdjPack == null) {
            return;
        }
        //每日签到奖励
        Wzdj.RpcClientSignInAll rpcClientSignInAll = (Wzdj.RpcClientSignInAll) wzdjPack.getBody();
        List<Wzdj.SignInData> signindatas = rpcClientSignInAll.getSignindatas();
        signindatas.forEach(signInData -> {
            Integer dayStatus = signInData.getStatus();
            if (dayStatus != null && dayStatus == 1) {
                WZDJSender.rpcServerSignInReward(signInData.getDay());//签到哪一天的奖励
            }
        });
        //每日签到累计奖励
        List<Wzdj.TotalSignInRewardData> totalsigninrewarddatas = rpcClientSignInAll.getTotalsigninrewarddatas();
        totalsigninrewarddatas.forEach(totalSignInRewardData -> {
            Integer index = totalSignInRewardData.getIndex();
            Integer rewardstatus = totalSignInRewardData.getRewardstatus();
            if (rewardstatus != null && rewardstatus == 2) {
                WZDJSender.rpcServerTotalSignInReward(index);
            }
        });
    }

    //每日探索任务奖励
    private void gainDayTaskAward() {
        //条件领取
        WZDJPack wzdjPack = WZDJCaller.getResCacheMap().get(1179649);
        if (wzdjPack == null) {
            return;
        }
        //分享任务加进度  有点离谱，已测试，其他任务不能客户端发加进度。有防范。
        WZDJSender.rpcServerWelfareMissionAddProgress("mr10001");
        //完成奖励
        WZDJSender.rpcServerMissionComplete("mr10001");

        Wzdj.RpcClientMissionList rpcClientMissionList = (Wzdj.RpcClientMissionList) wzdjPack.getBody();
        rpcClientMissionList.getAllinfo().forEach(typeMissionInfo -> {
            if (typeMissionInfo.getType() == 2) {//每日探索
                for (Wzdj.OneMissionInfo mission : typeMissionInfo.getMissions()) {
                    if (mission.getState() == 2) {//可领取
                        WZDJSender.rpcServerMissionComplete(mission.getMissid());
                        break;
                    }
                }
            } else if (typeMissionInfo.getType() == 13) {//每日探索 上方累计进度
                for (Wzdj.OneMissionInfo mission : typeMissionInfo.getMissions()) {
                    if (mission.getState() == 2) {//可领取
                        WZDJSender.rpcServerMissionComplete(mission.getMissid());
                        break;
                    }
                }
            } else {
                for (Wzdj.OneMissionInfo mission : typeMissionInfo.getMissions()) {
                    if (mission.getState() == 2) {//可领取
                        WZDJSender.rpcServerMissionComplete(mission.getMissid());
                        break;
                    }
                }
            }
        });
    }

    //免费金币奖励领取
    private void freeGoodsAward(Wzdj.ShopInfo shopInfo) {
        Integer freshCnt = shopInfo.getLeftrefreshcnt() != null ? shopInfo.getLeftrefreshcnt() : 0;
        List<Wzdj.GoodsInfo> freeGoldsGoodsInfoList = shopInfo.getGoodsinfo() != null ? shopInfo.getGoodsinfo() : new ArrayList<>();
        for (Wzdj.GoodsInfo goodsInfo : freeGoldsGoodsInfoList) {
            Integer goodsid = goodsInfo.getGoodsid() != null ? goodsInfo.getGoodsid() : 0;
            Integer buycnt = goodsInfo.getBuycnt() != null ? goodsInfo.getBuycnt() : 0;
            Integer salestate = goodsInfo.getSalestate() != null ? goodsInfo.getSalestate() : 0;
            if (goodsid == 1 && buycnt == 0 && salestate == 1) {
                WZDJSender.rpcServerShopBuy(shopInfo.getShopid(), 1);//免费金币领取
            }
        }
    }

    //每日商店免费商品奖励
    private void gainDayGoodsAward() {
        //免费金币领取
        Wzdj.ShopInfo freeShopGold = Stores.getInstance().getShopMap().get(10000);//免费金币商店
        if (freeShopGold != null) {
            freeGoodsAward(freeShopGold);
        }
        //免费钻石领取
        Wzdj.ShopInfo freeShopDiamond = Stores.getInstance().getShopMap().get(12001);//免费钻石领取
        if (freeShopDiamond != null) {
            freeGoodsAward(freeShopDiamond);
        }
    }

    //金币购买商品
    public void goldBuyGoods(){
        if (!Stores.getInstance().isLogin()){
            return;
        }
        //金币购买商品
        Wzdj.ShopInfo goldShopGoods = Stores.getInstance().getShopMap().get(10001);//金币购买商品
        if (goldShopGoods != null && !goldShopGoods.getGoodsinfo().isEmpty()) {
            List<Wzdj.GoodsInfo> goodsInfoList = goldShopGoods.getGoodsinfo() != null ? goldShopGoods.getGoodsinfo() : new ArrayList<>();
            for (int i = 0; i < goodsInfoList.size(); i++) {
                Wzdj.GoodsInfo goodsInfo = goodsInfoList.get(i);
                Integer goodsid = goodsInfo.getGoodsid() != null ? goodsInfo.getGoodsid() : 0;
                Integer buycnt = goodsInfo.getBuycnt() != null ? goodsInfo.getBuycnt() : 0;
                Integer maxBuyCnt = goodsInfo.getMaxbuycnt() != null ? goodsInfo.getMaxbuycnt() : 0;
                Integer salestate = goodsInfo.getSalestate() != null ? goodsInfo.getSalestate() : 0;
                Goods goods = Stores.getCfgGoods(goldShopGoods.getShopid(), goodsid);
                GoodsVO goodsVO = GoodsVO.of(goldShopGoods.getShopid(), goodsid, goods);

                String goodsStr = String.format("%s(%s)|%s(%s)|%s", goodsVO.getRewardName(), goodsVO.getRewardNum(), goodsVO.getCostName(), goodsVO.getCostNum(), salestate);

                if (salestate == 1) {//先判断状态为可买得
//                    Set<String> relicIdSet = Stores.relicCfgMap.keySet();
                    if ("gold".equals(goodsVO.getCostId())) {//花费金币直接买
                        WZDJSender.rpcServerShopBuy(goldShopGoods.getShopid(), goodsid);//商店可花金币购买，直接买
                    } else if ("diamond".equals(goodsVO.getCostId())) {//花费钻石
                        int costNum = 0;
                        try {
                            costNum = Integer.parseInt(goodsVO.getCostNum());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        String rewardId = goodsVO.getRewardId();//奖励道具id
                        String time = DateUtil.formatDateTime(new Date());
                        String buyMsg = time + costNum + "钻石 可买-> " + goodsStr;//
                        if (goodsVO.getRewardId().startsWith("fp_")) {//英雄碎片  直接买不展示
                            WZDJSender.rpcServerShopBuy(goldShopGoods.getShopid(), goodsid);//商店可兑换高级英雄碎片，直接兑换
                        } else if (rewardId.startsWith("r_") || "recruit_gem".equals(rewardId) || "mine_key".equals(rewardId) || "mythic_stone".equals(rewardId)) {
                            //英雄碎片，高级招募卷，锤子，万能碎片 看钻石价格选择购买
                            if (costNum > 0 && costNum < 300) {
                                WZDJSender.rpcServerShopBuy(goldShopGoods.getShopid(), goodsid);//商店根据钻石价格选择购买
                            } else {
                                WZDJMainFrame.consoleTextArea.append(buyMsg + "\n");
                            }
                        } else if (rewardId.startsWith("f_") || "recruit_key".equals(rewardId)) {//低级碎片,招募卷 不用买

                        } else {
                            WZDJMainFrame.consoleTextArea.append(buyMsg + "\n");
                        }
                    } else {
                        log.error("商店居然有不是花金币和钻石购买的商品" + goodsStr);
                    }
                }
            }


            //购买完本轮商品就刷新商店买下一轮
            WZDJSender.rpcServerShopRefresh(10001);
        }
    }

    //通行证等级奖励领取
    private void gainPassportInfoLevelAward() {

        WZDJSender.rpcServerPassportInfo();//通行证信息查询

        //条件领取
        WZDJPack wzdjPack = WZDJCaller.getResCacheMap().get(1376258);
        if (wzdjPack == null) {
            return;
        }
        Wzdj.RpcClientPassportInfo rpcClientPassportInfo = (Wzdj.RpcClientPassportInfo) wzdjPack.getBody();
        Wzdj.PassportInfo info = rpcClientPassportInfo.getInfo();
        Integer lv = info.getLv();
        if (lv == null || lv < 1) {
            return;
        }
        List<Integer> normalreward = info.getNormalreward();
        for (int i = 1; i <= lv; i++) {
            if (normalreward.contains(i)) {
                continue;
            }
            WZDJSender.rpcServerPassportNormalReward(i);
        }
    }

    //领取舞台达成奖励
    private void gainStageOkAward() {
        //条件领取
        WZDJPack wzdjPack = WZDJCaller.getResCacheMap().get(1441806);
        if (wzdjPack == null) {
            return;
        }
        Wzdj.RpcClientStageInfo rpcClientStageInfo = (Wzdj.RpcClientStageInfo) wzdjPack.getBody();
        List<Wzdj.StageRewardData> coopList = rpcClientStageInfo.getCoop();
        coopList.sort((o1, o2) -> o2.getStage() - o1.getStage());//排序
        List<Wzdj.StageRewardData> coophardList = rpcClientStageInfo.getCoophard();
        coophardList.sort((o1, o2) -> o2.getStage() - o1.getStage());//排序
        Integer battletype = rpcClientStageInfo.getBattletype() != null ? rpcClientStageInfo.getBattletype() : 0;
        if (battletype == 1) {
            for (Wzdj.StageRewardData stage : coopList) {
                Integer stage1 = stage.getStage();
                List<Integer> statusList = stage.getStatus() != null ? stage.getStatus() : new ArrayList<>();
                if (statusList.contains(1)) {
                    WZDJSender.rpcServerStageRewardGet(stage1, battletype);
                }
            }
        } else if (battletype == 2) {
            for (Wzdj.StageRewardData stage : coophardList) {
                Integer stage1 = stage.getStage();
                List<Integer> statusList = stage.getStatus() != null ? stage.getStatus() : new ArrayList<>();
                if (statusList.contains(1)) {
                    WZDJSender.rpcServerStageRewardGet(stage1, battletype);
                }
            }
        }
    }

    //个人信息里的免费礼包
    private void gainLimitShopDailyGift() {
        //暴力尝试领取
        //1.打开页面
        Wzdj.RpcServerUserView rpcServerUserView = new Wzdj.RpcServerUserView();
        rpcServerUserView.setUid(Stores.getInstance().getBasicInfo().getUid());
        PackUtil.send(Stores.getInstance().getHomeChannel(), rpcServerUserView);
        //2.读取红点
        Wzdj.RpcServerShopReadRed rpcServerShopReadRed = new Wzdj.RpcServerShopReadRed();
        rpcServerShopReadRed.setShopid(26001);
        PackUtil.send(Stores.getInstance().getHomeChannel(), rpcServerShopReadRed);
        //3.领取礼包
        Wzdj.RpcServerLimitShopDailyGiftGet rpcServerLimitShopDailyGiftGet = new Wzdj.RpcServerLimitShopDailyGiftGet();
        PackUtil.send(Stores.getInstance().getHomeChannel(), rpcServerLimitShopDailyGiftGet);
    }


    private void handleClearClick() {
        log.info("清屏被点击");
        consoleTextArea.setText("");
        homeChatArea.setText("");
        fightChatArea.setText("");
    }

    //购买金币商品
    private void handleBuyGoldGoodsClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        gainDayGoodsAward();//点击购买按钮
        goldBuyGoods();//金币购买商品
    }

    //刷新商店
    private void handleShopRefreshClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }

        if (Stores.getInstance().getFreshCnt().get() > 0) {//可刷新
            WZDJSender.rpcServerShopRefresh(10001);
        }

    }

    //招募 1 | 10次招募
    public static void handlerRecruitClick(int num) {
        if (!Stores.getInstance().isLogin()){
            return;
        }
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        WZDJSender.rpcServerFighterRecruit(num);
    }


    //统计日志耗时,清理日志耗时
    public static void handlerBtnClick(int num) {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }

        if (num == 1) {
            WZDJService.printTimeLog();
        } else if (num == 2) {
            WZDJCaller.methodTimeMap.clear();//重置耗时日志
        }
    }



    //竞技匹配
    private void handleBatMatchClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        WZDJService.startFight(4);//竞技匹配
    }

    boolean isBatCreating = false;

    private void handleBatCreateClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        isBatCreating = !isBatCreating;
        batCreateBtn.setText(isBatCreating ? "取消" : "竞技创建");
        if (isBatCreating) {
            WZDJSender.rpcServerFightRoomCreate(4);//创建竞技房间
        } else {
            WZDJSender.rpcServerFightRoomDestroy(Stores.getInstance().getRoomNum(), Stores.getInstance().getRoomNumType());//取消竞技房间
        }
    }

    private void handleBatJoinClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        log.info("竞技加入");
        String roomNum = batRoomField.getText();
        if (StrUtil.isBlank(roomNum) || roomNum.length() != 4) {
            WZDJMainFrame.consoleTextArea.append("房间号必须4位" + "\n");
            return;
        }
        WZDJSender.rpcServerFightRoomJoin(roomNum, 4);//加入竞技房间
    }

    boolean isBatFinding = false;

    private void handleBatFindClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        isBatFinding = !isBatFinding;
        batFindRoomBtn.setText(isBatFinding ? "取消" : "竞技找房");
        if (isBatFinding) {
            log.info("开始竞技找房");

            for (int i = 1000; i < 1_0000; i++) {
                if (!isBatFinding) {
                    break;
                }
                String roomNum = i + "";
                WZDJSender.rpcServerFightRoomJoin(roomNum, 4);//加入竞技房间
            }
        } else {
            log.info("取消竞技找房");
        }
    }


    private void handleWithMatchBtnClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        if (Stores.getInstance().getEnergy().get() < 5) {
            WZDJMainFrame.consoleTextArea.append("体力不足，请先恢复体力" + "\n");
            return;
        }
        WZDJService.startFight(1);//普通合作匹配
    }

    boolean isWithCreating = false;

    private void handleWithCreateClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        isWithCreating = !isWithCreating;
        withCreateBtn.setText(isWithCreating ? "取消" : "合作创建");
        if (isWithCreating) {
            log.info("创建合作房间");
            WZDJSender.rpcServerFightRoomCreate(1);//创建合作房间
        } else {
            log.info("取消合作房间");
            WZDJSender.rpcServerFightRoomDestroy(Stores.getInstance().getRoomNum(), 1);//取消合作房间
        }
    }

    private void handleWithJoinClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        log.info("合作加入");
        String roomNum = withRoomField.getText();
        if (StrUtil.isBlank(roomNum) || roomNum.length() != 4) {
            log.error("房间号必须4位");
            return;
        }
//        log.info(roomNum);
        WZDJSender.rpcServerFightRoomJoin(roomNum, 1);//合作加入
    }

    boolean isWithFinding = false;

    private void handleWithFindClick() {
        if (Stores.getInstance().getHomeChannel() == null) {
            WZDJMainFrame.consoleTextArea.append("请先登录，并连接服务器" + "\n");
            return;
        }
        isWithFinding = !isWithFinding;
        withFindRoomBtn.setText(isWithFinding ? "取消" : "合作找房");
        if (isWithFinding) {
            log.info("开始合作找房");

            for (int i = 1000; i < 1_0000; i++) {
                if (!isWithFinding) {
                    break;
                }
                String roomNum = i + "";
                WZDJSender.rpcServerFightRoomJoin(roomNum, 1);//暴力找房合作模式
            }
        } else {
            log.info("取消合作找房");
        }
    }

    private void handleCallBtnClick() {
        if (Stores.getInstance().getFightChannel() == null) {
            log.error("请先进入房间");
            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
            return;
        }
        if (Stores.getInstance().getIsFight().get()){
            log.info("召唤");
            WZDJSender.rpcServerFightFighterCall();//按钮点击召唤
        }
    }

    private void handleGambleButtonClick(int buttonNumber) {
        if (Stores.getInstance().getFightChannel() == null) {
            log.error("请先进入房间");
            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
            return;
        }
        if (Stores.getInstance().getIsFight().get()){
            log.info("赌博" + buttonNumber + "被点击");
            int quality = buttonNumber + 1;
            WZDJSender.rpcServerFightBet(quality);//打赌颜色
        }

    }

    //强化
    private void handleEnhanceButtonClick(int buttonNumber) {
        if (Stores.getInstance().getFightChannel() == null) {
            log.error("请先进入房间");
            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
            return;
        }
        if (Stores.getInstance().getIsFight().get()){
            log.info("强化" + buttonNumber + "被点击");
            WZDJSender.rpcServerFightEnhance(buttonNumber);
        }
    }

    //副本召唤
    private void handleChallengeClick() {
        if (Stores.getInstance().getFightChannel() == null) {
            log.error("请先进入房间");
            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
            return;
        }
        if (Stores.getInstance().getIsFight().get()){
            WZDJSender.rpcServerFightMonsterEliteCall();//副本召唤
        }
    }


//    private void handleRemove1Click() {
//        if (Stores.getInstance().getFightChannel() == null) {
//            log.error("请先进入房间");
//            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
//            return;
//        }
//        if (Stores.getInstance().getIsFight().get()){
//            log.info("清理一级");
//            for (Map.Entry<String, CopyOnWriteArrayList<Wzdj.FightActorData>> entry : Stores.getInstance().getMyActorMap().entrySet()) {
//                String actorId = entry.getKey();
//                if (!actorId.startsWith("f_1")) {
//                    continue;
//                }
//                CopyOnWriteArrayList<Wzdj.FightActorData> actorDataList = entry.getValue();
//                for (Wzdj.FightActorData fightActorData : actorDataList) {
//                    WZDJService.remove(fightActorData);
//                }
//            }
//        }
//
//    }
//
//    private void handleRemove2Click() {
//        if (Stores.getInstance().getFightChannel() == null) {
//            log.error("请先进入房间");
//            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
//            return;
//        }
//        if (Stores.getInstance().getIsFight().get()){
//            log.info("清理二级");
//
//            Stores.getInstance().getMyActorMap().forEach((actorId, actorDataList) -> {
//                if (actorId.startsWith("f_2")) {
//                    for (Wzdj.FightActorData fightActorData : actorDataList) {
//                        WZDJService.remove(fightActorData);
//                    }
//                }
//            });
//        }
//
//    }
//
//    private void handleRemoveAllClick() {
//        if (Stores.getInstance().getFightChannel() == null) {
//            log.error("请先进入房间");
//            WZDJMainFrame.consoleTextArea.append("请先登录，并先进入房间" + "\n");
//            return;
//        }
//        if (Stores.getInstance().getIsFight().get()){
//            log.info("清理所有");
//            Stores.getInstance().getMyActorMap().forEach((actorId, actorDataList) -> {
//                for (Wzdj.FightActorData fightActorData : actorDataList) {
//                    WZDJService.remove(fightActorData);
//                }
//            });
//        }
//
//    }

    private void handleTestBtnClick(int buttonNumber) {
        if (Stores.getInstance().getFightChannel() == null) {
            log.error("请先进入房间");
            return;
        }
        if (buttonNumber == 1) { //自动80召唤
            Stores.getInstance().setAutoCall(!Stores.getInstance().isAutoCall());
        } else if (buttonNumber == 2) {
            Stores.getInstance().setAutoCombination(!Stores.getInstance().isAutoCombination());
        } else if (buttonNumber == 3) {
            Stores.getInstance().setAutoMythic(!Stores.getInstance().isAutoMythic());
        } else if (buttonNumber == 4) {
            Stores.getInstance().setAutoMove(!Stores.getInstance().isAutoMove());
        } else if (buttonNumber == 5) {
            Stores.getInstance().setAutoRemove(!Stores.getInstance().isAutoRemove());
        } else if (buttonNumber == 6) {
            Stores.getInstance().setAutoGambling(!Stores.getInstance().isAutoGambling());
        } else if (buttonNumber == 7) {
            Stores.getInstance().setAutoStrengthen(!Stores.getInstance().isAutoStrengthen());
        } else if (buttonNumber == 8) {
            Stores.getInstance().setAutoHunting(!Stores.getInstance().isAutoHunting());
        } else if (buttonNumber == 9) {
            Stores.getInstance().setAccelerate(!Stores.getInstance().isAccelerate());
            if (Stores.getInstance().isAccelerate()) {
                WZDJSender.rpcServerFightAccelerate(2);
            } else {
                WZDJSender.rpcServerFightAccelerate(1);
            }
        } else {
//            Stores.getInstance().setAutoRemove(!Stores.getInstance().isAutoRemove());
        }
    }







}
